package com.yh.workbill.ui.countinfo.mvp;

import android.content.SharedPreferences;
import android.media.MediaScannerConnection;
import android.os.Environment;

import com.yh.workbill.App;
import com.yh.workbill.AppGlobals;
import com.yh.workbill.base.IBaseModel;
import com.yh.workbill.db.UserInfo;
import com.yh.workbill.db.UserInfoDao;
import com.yh.workbill.model.WorkBill;
import com.yh.workbill.network.BaseCallback;
import com.yh.workbill.network.OkHttpService;
import com.yh.workbill.ui.search.mvp.Search_Model;
import com.yh.workbill.utils.FileUtils;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import androidx.arch.core.executor.ArchTaskExecutor;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;

import static com.yh.workbill.utils.Config.SP_USER;

public class CountInfo_Model {

    interface OnFileCallBack extends IBaseModel.Fail {
        void onSuccess(String data);
    }

    interface OnFileDownCalBack extends IBaseModel.Fail {
        void onSuccess(String data, String url);
    }


    public void getCountInfo(String companyname, String unitname, String year, String month, int pageindex, int pagenumber, Search_Model.SearchCallBack callBack) {
        ArchTaskExecutor.getIOThreadExecutor().execute(() -> {
            SharedPreferences sp = AppGlobals.getApplication().getSharedPreferences(SP_USER, AppGlobals.getApplication().MODE_PRIVATE);
            String phone = sp.getString("phone", "");
            UserInfoDao userInfoDao = App.appDataBase.getUserInfoDao();
            UserInfo singleUserInfo = userInfoDao.getSingleUserInfo(phone);
            OkHttpService.getInstance().getSearchCountInfo(singleUserInfo.getUuid(), companyname, unitname, year, month, pageindex, pagenumber, new BaseCallback<List<WorkBill>>() {
                @Override
                public void accessSuccess(int code, String msg, List<WorkBill> data) {
                    ArchTaskExecutor.getMainThreadExecutor().execute(() -> {
                        if (code == 200) {
                            callBack.getData(data);
                        } else {
                            callBack.fail(msg);
                        }
                    });
                }

                @Override
                public void accessFailure(String errorMessage) {
                    ArchTaskExecutor.getMainThreadExecutor().execute(() -> callBack.fail(errorMessage));
                }
            });
        });
    }

    public void downFile(String json, String year, String month, String companyname, String unitname, int pageindex, int pagenumber, OnFileCallBack callBack) {

        ArchTaskExecutor.getIOThreadExecutor().execute(() -> {
            SharedPreferences sp = AppGlobals.getApplication().getSharedPreferences(SP_USER, AppGlobals.getApplication().MODE_PRIVATE);
            String phone = sp.getString("phone", "");
            UserInfoDao userInfoDao = App.appDataBase.getUserInfoDao();
            UserInfo singleUserInfo = userInfoDao.getSingleUserInfo(phone);

            OkHttpService.getInstance().postSearchCountInfo(singleUserInfo.getUuid(), phone, json, year,
                    month, companyname, unitname, pageindex, pagenumber, new BaseCallback<String>() {
                        @Override
                        public void accessSuccess(int code, String msg, String data) {
                            ArchTaskExecutor.getMainThreadExecutor().execute(() -> {
                                if (code == 200) {
                                    callBack.onSuccess(data);
                                } else {
                                    callBack.fail(msg);
                                }
                            });
                        }

                        @Override
                        public void accessFailure(String errorMessage) {
                            ArchTaskExecutor.getMainThreadExecutor().execute(() -> callBack.fail(errorMessage));
                        }
                    });
        });

    }

    public void download(String path, OnFileDownCalBack callBack) {
        String url = "https://oss.ysmart.xyz/" + path;
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();

        Call call = OkHttpService.okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                callBack.fail(e.getMessage());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String dirName = FileUtils.addExcelPath();
                File file = new File(dirName);
                if (!file.exists()) {
                    file.mkdir();
                }
                File excelFile = new File(file.getPath(), path);
                if (response != null) {
                    InputStream is = response.body().byteStream();
                    FileOutputStream fos = new FileOutputStream(excelFile);
                    int len = 0;
                    byte[] buffer = new byte[2048];
                    while (-1 != (len = is.read(buffer))) {
                        fos.write(buffer, 0, len);
                    }
                    fos.flush();
                    fos.close();
                    is.close();
                }
                callBack.onSuccess(excelFile.getAbsolutePath(), url);
            }
        });
    }

}
